package com.ycsj.goldmedalnewconcept.common.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.OnloadingMoreListener;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.dialog.AlertDialogUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.NoticeRvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.NoticeInfo;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 通用的公告页面
 */
public class NoticeActivity extends BaseActivity implements SrfManager.OnPullRefreshListener, OnloadingMoreListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoadingView;

    //空视图
    private View emptyView;

    //界面刷新的标识
    public static final int UPDATE = 0x551;

    //数据集合
    private List<NoticeInfo.ListBean> oldDatas;

    //分页
    private int page = 1;

    //适配器
    private NoticeRvAdapter adapter;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_notice;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        initStateBar();

        //初始化标题栏
        initTitle();

        //初始化下拉刷新控件
        initSrf();


        //请求数据
        http(BqaManager.NORML);

    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("公  告");
        if ("3".equals(AccountUtils.getRole(this))) {
            lvEdit.setVisibility(View.VISIBLE);
            lvEdit.setImageResource(R.drawable.edit);
        } else {
            lvEdit.setVisibility(View.GONE);
        }

    }


    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }

    /**
     * 设置列表
     */
    private void initRv() {
        rlLoadingView.setVisibility(View.GONE);

        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("暂无公告内容");
        adapter = new NoticeRvAdapter(this, R.layout.common_rv_notice, oldDatas);

        BqaManager.setRv(emptyView, NoticeActivity.this, adapter, rv, NoticeActivity.this);

        //校长可删除公告
        if ("3".equals(AccountUtils.getRole(this))) {

            adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                    AlertDialogUtil.newInstance(NoticeActivity.this)
                            .setCancelable(true) //点击返回键和空白处是否可以消失
                            .negativeText("")//设置取消按钮的文字,如果设置为空时则不显示取消按钮
                            //确定按钮的点击事件
                            .positive(new AlertDialogUtil.OnAlertPositiveListener() {
                                @Override
                                public void onPositiveClick(int i) {
                                    doDeletNotice(position);
                                }
                            })//取消按钮的点击事件
                            .showDialog("确定删除该条公告吗?");

                    return false;
                }
            });
        }
    }


    /**
     * 请求服务器数据的方法
     *
     * @param method
     */
    private void http(final int method) {
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            page = 1;
        } else {
            page++;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("page", page + "");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.NOTICE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    NoticeInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, NoticeInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            List<NoticeInfo.ListBean> newDatas = info.getList();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {

                                    oldDatas = new ArrayList<>();

                                    oldDatas.addAll(newDatas);

                                    //设置数据
                                    initRv();

                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                }
                            }
                        } else {

                            StateCodeUtils.showSateCode(info.getState());
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }

                    } else {
                        Log.i("test", Constants.EMPTY);
                    }

                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 删除公告的方法
     */
    private void doDeletNotice(final int position) {
        CustomDialogManager.show(this, "删除中...");
        //删除的操作
        Map<String, String> map = new HashMap<>();

        map.put("type", "6");

        map.put("acc", AccountUtils.getAccount(BaseApplication.context));

        map.put("role", "3");

        map.put("rowid", oldDatas.get(position).getRowid() + "");

        map.put("platform", "2");

        HttpUtils.post(HttpAddress.DELETENOTICE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast("服务器异常,上传失败", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!android.text.TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //删除该条记录,刷新界面
                            oldDatas.remove(position);
                            adapter.notifyDataSetChanged();
                            //返回成功
                            UiUtils.Toast("删除成功", false);
                        } else {
                            UiUtils.Toast("删除失败,返回异常码是:" + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.lv_edit, R.id.iv_back})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.lv_edit) {
            //发布公告
            UiUtils.startActivity(this, SendNoticeActivity.class);
        }
    }

    /**
     * 事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {

        //更新界面的消息
        if (null != busInfo && busInfo.type == UPDATE) {
            http(BqaManager.PULLREFRESH);
        }
    }


    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        http(BqaManager.PULLREFRESH);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        http(BqaManager.LOADINDGMORE);
    }

}
